<?php

namespace app\admin\controller;
use think\Db;
use app\common\controller\Backend;
use app\api\controller\Information;
use app\api\controller\Push;
use app\common\model\ChatRoom as ChatRoomModel;
use app\common\model\User as UserModel;

/**
 * 平台公告消息
 *
 * @icon fa fa-circle-o
 */
class Notice extends Backend
{

    /**
     * Notice模型对象
     * @var \app\admin\model\Notice
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Notice;

    }

    

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
/**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            $where = "is_jin = '0'";
            $where.= " AND logout = '0'";
            $field = "user_id,username,identification,android_registration_id,ios_registration_id";
            $android_arr = UserModel::where($where)->where("android_registration_id","<>","")->field($field)->select();
            if($android_arr){
                foreach ($android_arr as &$value){
                    Db::name("notice_task")->insert([
                        "user_id" => $value["user_id"],
                        "type" => 1,
                        "title" => $params["title"],
                        "content" => $params["content"],
                        "jg_registration_id" => $value["android_registration_id"],
                        "hx_identification" => $value["identification"],
                        "create_time" => time(),
                    ]);
                }
            }
            $ios_arr = UserModel::where($where)->where("ios_registration_id","<>","")->field($field)->select();
            if($ios_arr){
                foreach ($ios_arr as &$value){
                    Db::name("notice_task")->insert([
                        "user_id" => $value["user_id"],
                        "type" => 1,
                        "title" => $params["title"],
                        "content" => $params["content"],
                        "jg_registration_id" => $value["ios_registration_id"],
                        "hx_identification" => $value["identification"],
                        "create_time" => time(),
                    ]);
                }
            }
            $hx_arr = UserModel::where($where)->where("identification","<>","")->field($field)->select();
            if($hx_arr){
                foreach ($hx_arr as &$value){
                    Db::name("notice_task")->insert([
                        "user_id" => $value["user_id"],
                        "type" => 2,
                        "title" => $params["title"],
                        "content" => $params["content"],
                        "jg_registration_id" => $value["ios_registration_id"],
                        "hx_identification" => $value["identification"],
                        "create_time" => time(),
                    ]);
                }
            }
            Db::commit();
            // $Information = new Information;
            // $Information->releaseNotice();
            // $this->releaseNotice1();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /*
     * 发公告
     * @ApiMethod (POST)
     * @path api/information/releaseNotice
     * */
    public function releaseNotice1()
    {
        $where = "is_jin = '0'";
        $where.= " AND logout = '0'";
        $field = "user_id,username,identification,uuid";
        $info = db('notice')->order('id desc')->find();
        $notice=$info['content'];
        $notice=get_image_url($notice,protocol_name() . '://' . $_SERVER['SERVER_NAME']);
        $content = [
            "notice" => $notice,
        ];
        $pageSize = 600; // 每次处理的数据量
        $page = 1; // 初始化页数
        do {
            $users =UserModel::where($where)->field($field)->limit(($page - 1) * $pageSize, $pageSize)->select();
            // 如果查询到数据，则逐条处理
            if (!empty($users)) {
                foreach ($users as &$user) {
                    if($user['identification']){
                        ChatRoomModel::sendToUser('EWx24UyplePq3vR5',$user['identification'],$content);
                    }
                }
            }
            $page++; // 增加页数，准备处理下一页数据
            // 如果查询的数据数量少于$pageSize，说明数据已处理完毕
        } while (count($users) === $pageSize);
        $this->success("请求成功");
    }

}
